# -.- coding: utf-8 -.-

#from profiles.models import *
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from django.conf import settings
from django.core.files.storage import FileSystemStorage
from os import path

fs = FileSystemStorage(location=settings.BASE_DIR)

def crea_path (instance, filename):
    import string
    valid_chars = "-_.()%s%s" % (string.ascii_letters, string.digits)
    usr = ''.join(c for c in instance.user.username if c in valid_chars)
    nuevonombre = usr+path.splitext(filename)[-1]
    #nuevonombre = ''.join(c for c in nuevonombre if c in valid_chars)
    p = path.join("profiles", usr, nuevonombre)
    return p

class UserProfile(models.Model):
    """
        
    """
    user = models.ForeignKey(User, unique=True, related_name="%(class)s_related")
    descripcion = models.TextField(blank=True, null=True)
    foto = models.ImageField(_(u'Foto de perfil'), upload_to = crea_path)
    #thumbnail = models.ImageField(upload_to='profile_thumb', blank=True, null=True, editable=False)
    #TODO: EN EL FUTURO, PARA AÑADIR LISTA DE AMIGOS, PONER UN CAMPO DE CLAVE EXTERNA A OTROS USUARIOS, "amigos"
     
    def __unicode__(self):
        return self.user

    #def save(self, force_insert=False, force_update=False):
    #    import os
    #    #get mtime stats from file
    #    thumb_update = False
    #
    #    # Does a thumbnail exist?
    #    if self.thumbnail:
    #    # Does it actually exist?
    #        try:
    #        # If so, compare it to the latest foto
    #            statinfo1 = os.stat(self.foto.path)
    #            statinfo2 = os.stat(self.thumbnail.path)
    #            if statinfo1 > statinfo2:
    #                thumb_update = True
    #        # If not, update the thumbnail
    #        except OSError:
    #            thumb_update = True
    #
    #    if self.foto and not self.thumbnail or thumb_update:
    #        from PIL import Image
    #        THUMB_SIZE = (150, 150)
    #        #self.thumbnail = self.foto
    #
    #        image = Image.open(self.foto.path)
    #
    #        if image.mode not in ('L', 'RGB'):
    #            image = image.convert('RGB')
    #
    #        image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
    #        (head, tail) = os.path.split(self.foto.path)
    #        (a, b) = os.path.split(self.foto.name)
    #        
    #        image.save(head + 'thumb_' + tail)
    #
    #        self.thumbnail = a + 'thumb_' + b
    #        print self.thumbnail
    #
    #    super(UserProfile, self).save()